<template>
  <div class="app-container">
    <el-row :gutter="8">
      <!--主题域数据-->
      <el-col :span="4" :xs="24">
        <AreaTable ref="areaTable" :pageType="pageType" :btnShow="btnShow" @change="handleChangeArea"></AreaTable>
      </el-col>
      <!--模型定义-->
      <el-col :span="20" :xs="24">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>模型</span>
              <el-row>
                <el-input v-model="modelParams.searchValue" placeholder="名称/编码" suffix-icon="Search"
                          style="width: 140px;margin: 0 3px;vertical-align: middle;" @change="loadModelList(1)"/>
                <el-button-group v-if="btnShow.edit">
                  <el-tooltip content="新增" placement="top">
                    <el-button icon="Plus" @click="handleAddModel"></el-button>
                  </el-tooltip>
                  <el-tooltip content="提交" placement="top">
                    <el-button icon="Select" :disabled="nonCheck()" @click="handleSubmitModel"></el-button>
                  </el-tooltip>
                  <el-tooltip content="变更" placement="top">
                    <el-button icon="Paperclip" @click="handleUpgradeModel"></el-button>
                  </el-tooltip>
                </el-button-group>
                <el-button-group v-if="btnShow.audit">
                  <el-tooltip content="通过" placement="top">
                    <el-button icon="SuccessFilled" :disabled="nonCheck()" @click="handleApproveModel"></el-button>
                  </el-tooltip>
                  <el-tooltip content="拒绝" placement="top">
                    <el-button icon="CircleCloseFilled" :disabled="nonCheck()" @click="handleRejectModel"></el-button>
                  </el-tooltip>
                </el-button-group>
              </el-row>
            </div>
          </template>
          <el-row>
            <el-table
                v-loading="modelLoading"
                :data="modelList"
                @selection-change="handleSelectionChange"
                border
                fit
            >
              <el-table-column type="selection" width="55" align="center"/>
              <el-table-column label="模型名称（编码）">
                <template #default="scope">
                  <span>{{ scope.row.name }}&nbsp;&nbsp;<el-tag size="small" type="info">{{
                      scope.row.code
                    }}</el-tag></span>
                </template>
              </el-table-column>
              <el-table-column label="类型" width="100">
                <template #default="scope">
                  <dict-tag :options="sys_def_type" :value="scope.row.dataType"/>
                </template>
              </el-table-column>
              <el-table-column label="分类" width="80">
                <template #default="scope">
                  <dict-tag :options="sys_def_switch" :value="scope.row.classifySw"/>
                </template>
              </el-table-column>
              <el-table-column label="分类模板" width="80">
                <template #default="scope">
                  <dict-tag :options="sys_def_switch" :value="scope.row.classPropSw"/>
                </template>
              </el-table-column>
              <el-table-column label="引用模型" :show-overflow-tooltip="true">
                <template #default="scope">
                  <span v-if="scope.row.linkCode === '-'">默认分类</span>
                  <span v-else-if="scope.row.linkCode != null && scope.row.linkCode != '' ">
                    {{ scope.row.linkName }}
                    <el-tag size="small" type="info">{{ scope.row.linkCode }}</el-tag>
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="默认访问">
                <template #default="scope">
                  <dict-tag :options="sys_user_vip" :value="scope.row.vipLevel"/>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button-group size="small">
                    <el-button v-if="scope.row.auditFlag === 1" icon="Edit" @click="handleEditModel(scope.row)"/>
                    <el-button v-if="scope.row.auditFlag === 1" icon="Delete" @click="handleDeleteModel(scope.row)"/>
                    <el-button v-if="scope.row.auditFlag > 1" icon="View" @click="handleViewModel(scope.row)"/>
                    <el-button v-if="scope.row.auditFlag === 3" icon="Promotion" @click="handleDeployModel(scope.row)"/>
                  </el-button-group>
                </template>
              </el-table-column>
            </el-table>
            <pagination
              v-show="total > 0"
              :total="total"
              v-model:page="pagination.pageNum"
              v-model:limit="pagination.pageSize"
              @pagination="loadModelList(1)"
            />
          </el-row>
        </el-card>
      </el-col>
    </el-row>
    <!--模型配置弹出窗口-->
    <ModelConfig ref="modelConfigDef" @refresh="loadModelList(1)" />
  </div>
</template>

<script name="Model">
import { getCurrentInstance, onMounted, reactive, toRefs } from 'vue';
import AreaTable from '@/views/module/area/table.vue';
import ModelConfig from '@/views/module/model/config.vue';
import typeUtil, { PageTypeEnum } from '@/store/enums/PageTypeEnum';
import modelApi from '@/api/module/model';
import ux from './data';

export default {
  components: {
    AreaTable,
    ModelConfig,
  },
  setup() {
    const { proxy } = getCurrentInstance();
    const query = proxy.$route.query;
    const queryPage = parseInt(query['p'].toString());
    const {
      sys_def_switch,
      sys_user_vip,
      sys_def_type
    } = proxy.useDict('sys_def_switch', 'sys_user_vip', 'sys_def_type');

    const getAuditFlag = (listType) => {
        return Math.floor(listType / 10);
    };

    const vueData = reactive({
      pageType: queryPage,
      areaList: [],
      modelLoading: false,
      modelList: [],
      checkList: [],
      pagination: {
        pageNum: 1,
        pageSize: 10,
      },
      modelParams: {
        searchValue: '',
        areaCode: '',
        auditFlag: getAuditFlag(queryPage),
      },
      total: 0,
      btnShow: typeUtil.getBtnShow(queryPage),
    });
    const loadModelList = (page) => {
      if (page != null) {
        vueData.pagination.pageNum = page;
      }
      const pageQuery= {
        ...vueData.pagination,
        queryParam: {
          ...vueData.modelParams,
        },
      };
      vueData.modelLoading = false;
      modelApi.listModel(pageQuery).then(res => {
        vueData.modelLoading = false;
        vueData.modelList = res.rows;
        vueData.total = res.total;
      });
    }

    const handleChangeArea = (areaCode) => {
      vueData.modelParams.areaCode = areaCode;
      loadModelList(1);
    }

    function handleSelectionChange(checkList) {
      vueData.checkList = checkList;
    }

    function handleAddModel() {
      const model = Object.assign(ux.initData(), { areaCode: vueData.modelParams.areaCode })
      proxy.$refs['modelConfigDef'].show(PageTypeEnum.ADD, model);
    }

    function handleEditModel(model) {
      proxy.$refs['modelConfigDef'].show(PageTypeEnum.EDIT, model);
    }

    function handleViewModel(model) {
      proxy.$refs['modelConfigDef'].show(PageTypeEnum.QUERY, model);
    }

    function handleUpgradeModel() {
      // 弹出选择，后续开发
      proxy.$modal.msgWarning('...模型变更...');
    }

    function nonCheck() {
      return vueData.checkList == null || vueData.checkList.length == 0;
    }

    function handleSubmitModel() {
      modelApi.submitModel(vueData.checkList).then((res) => {
        console.log(res.data);
        proxy.$modal.msgSuccess('模型提交成功');
        loadModelList(1);
      }, () => {
        proxy.$modal.msgWarning('模型提交失败');
      });
    }

    function handleRejectModel() {
      modelApi.rejectModel(vueData.checkList).then((res) => {
        proxy.$modal.msgSuccess('模型拒绝成功');
        loadModelList(1);
      }, () => {
        proxy.$modal.msgWarning('模型拒绝失败');
      });
    }

    async function handleApproveModel() {
      modelApi.approveModel(vueData.checkList).then((res) => {
        proxy.$modal.msgSuccess('模型通过成功');
        loadModelList(1);
      }, () => {
        proxy.$modal.msgWarning('模型通过失败');
      });
    }

    function handleDeployModel(model) {
      const list = [model];
      modelApi.deployModel(list).then((res) => {
        proxy.$modal.msgSuccess('模型发布成功');
        loadModelList(1);
      }, () => {
        proxy.$modal.msgWarning('模型发布失败');
      });
    }

    function handleDeleteModel(model) {
      proxy.$modal.confirm('是否确认删除模型？').then(function () {
        return modelApi.delModel(model.uid);
      }).then(() => {
        loadModelList(1);
        proxy.$modal.msgSuccess('删除成功');
      }).catch(() => {
      });
    }

    onMounted(() => {
      proxy.$refs['areaTable'].loadAreaList();
    });

    return {
      PageTypeEnum,
      sys_def_switch,
      sys_user_vip,
      sys_def_type,
      ...toRefs(vueData),
      nonCheck,
      loadModelList,
      handleSelectionChange,
      handleChangeArea,
      handleAddModel,
      handleEditModel,
      handleViewModel,
      handleDeployModel,
      handleUpgradeModel,
      handleSubmitModel,
      handleDeleteModel,
      handleRejectModel,
      handleApproveModel,
    }
  },
}
</script>

<style scoped>
div.el-dialog__body {
  padding: 5px 5px;
}
</style>